package com.seasun.xg.lamp.web;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.seasun.xg.lamp.repo.LogVo;

@Service
public final class WebService {

	@Autowired
	private WebRepository repo;

	public List<LogVo> latest(int count) {
		return repo.getLatestSeq(count);
	}

	public List<LogVo> search(int count, String deviceId, String localIp, String publicIp, String level, String appName,
			String appVersion, String content) {
		return repo.search(count, makeQueryString(deviceId), makeQueryString(localIp), makeQueryString(publicIp),
				makeQueryString(level), makeQueryString(appName), makeQueryString(appVersion),
				makeQueryString(content));
	}

	public List<LogVo> get(String seq) {
		return repo.findBySeqOrderByDbTimestampAsc(seq);
	}

	private static String makeQueryString(String value) {
		String str = StringUtils.trimWhitespace(value);

		if (value.isEmpty()) {
			return "";
		} else if ((str.startsWith("\"") && str.endsWith("\""))
				|| (str.startsWith("'") && str.endsWith("'"))) {
			return str.substring(1, str.length() - 1);
		}

		return "%" + str + "%";
	}

}
